package com.hjm.common.api.ls.leshua;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.*;

public class LsShuaHttpUtil {

    public static String doGet(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";

        try {
            httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
            httpGet.setConfig(requestConfig);
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException var22) {
            var22.printStackTrace();
        } catch (IOException var23) {
            var23.printStackTrace();
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException var21) {
                    var21.printStackTrace();
                }
            }

            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException var20) {
                    var20.printStackTrace();
                }
            }

        }

        return result;
    }


    public static JSONObject doPost(String url, String jsonStrBody, Map<String, Object> headerMap) {
        JSONObject json = null;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = "";
        httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPost.setConfig(requestConfig);
        //post 请求Content-Type 一定要设置成application/json
        //默认Content-Type 为application/x-www-form-urlencoded
        httpPost.addHeader("Content-Type", "application/json");
        if (null != headerMap && headerMap.size() > 0) {
            Set<Map.Entry<String, Object>> entrySet = headerMap.entrySet();
            Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
            Map.Entry mapEntry = null;

            while (iterator.hasNext()) {
                mapEntry = (Map.Entry) iterator.next();
                httpPost.addHeader((String) mapEntry.getKey(), mapEntry.getValue().toString());
            }
        }

        if (!StringUtils.isEmpty(jsonStrBody)) {
            httpPost.setEntity(new StringEntity(jsonStrBody, "utf-8"));
        }

        try {
            httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity);
            json = JSONObject.parseObject(result);
        } catch (ClientProtocolException var27) {
            var27.printStackTrace();
        } catch (IOException var28) {
            var28.printStackTrace();
        } finally {
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException var26) {
                    var26.printStackTrace();
                }
            }

            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException var25) {
                    var25.printStackTrace();
                }
            }

        }

        return json;
    }

    public static String doGet(String url, Map<String, Object> params) {
        long start = System.currentTimeMillis();
        StringBuffer param = new StringBuffer();
        int i = 0;

        String result;
        for (Iterator i$ = params.keySet().iterator(); i$.hasNext(); ++i) {
            result = (String) i$.next();
            if (i == 0) {
                param.append("?");
            } else {
                param.append("&");
            }

            param.append(result).append("=").append(params.get(result));
        }

        String apiUrl = url + param;
        result = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        int statusCode = -999;

        try {
            HttpGet httpPost = new HttpGet(apiUrl);
            HttpResponse response = httpclient.execute(httpPost);
            statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                result = IOUtils.toString(instream, "UTF-8");
            }
        } catch (Exception var17) {
            var17.printStackTrace();
        } finally {
            if (httpclient != null) {
                HttpClientUtils.closeQuietly(httpclient);
            }

        }

        return result;
    }

    public static JSONObject postForm(String url, Map<String, Object> paramMap, Map<String, Object> header) throws Exception {
        String result = postForm(url, paramMap, header, 30000);
        return JSONObject.parseObject(result);
    }

    public static String postForm(String url, Map<String, Object> paramMap, Map<String, Object> header, int timeout) throws Exception {
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        String result = "";
        try {
            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            cm.setDefaultMaxPerRoute(20);
            cm.setMaxTotal(200);
            client = HttpClients.custom().setConnectionManager(cm).build();
            List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
            for (Map.Entry<String, Object> stringObjectEntry : paramMap.entrySet()) {
                params.add(new BasicNameValuePair(stringObjectEntry.getKey(), stringObjectEntry.getValue().toString()));
            }
            HttpPost httppost = new HttpPost(url);
            httppost.setEntity(new UrlEncodedFormEntity(params, Charset.forName("UTF-8")));
            if (header != null) {
                for (Map.Entry<String, Object> entry : header.entrySet()) {
                    httppost.addHeader(entry.getKey(), entry.getValue().toString());
                }
            }

            // 设置请求超时，连接超时和数据传输超时
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(timeout)
                    .setConnectTimeout(timeout)
                    .setSocketTimeout(timeout).build();
            httppost.setConfig(requestConfig);

            response = client.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                result = EntityUtils.toString(responseEntity, "UTF-8");
            } else {
                throw new RuntimeException("Response status:" + statusCode);
            }
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }
        }
        return result;
    }
}
